﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ZhimeiSoft.Framework.Client.Base;
using ZhimeiSoft.Framework.Common.Enums;

using ZhimeiSoft.CharmManager.DOL;
using ZhimeiSoft.CharmManager.Client.Manager;
using ZhimeiSoft.CharmManager.Client.Forms.Control.ServiceItem;
using ZhimeiSoft.Framework.Client.Utils;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;

namespace ZhimeiSoft.CharmManager.Client.Forms.Control.ServiceItem
{
    public partial class ServiceItemControl : UserControl
    {
        private string sDefaultRowFilter = "";
        private bool bServiceItemEditMode = true;
        private bool bServiceItemCategoryEditMode = true;
        private bool bShowServiceitemFilterBar = false;
        private DataSet dsServiceItem;
        private DataSet dsServiceItemCategory;

        /// <summary>
        /// 是否显示服务项目过滤工具栏
        /// </summary>
        public bool ShowServiceItemFilterBar
        {
            get { return bShowServiceitemFilterBar; }
            set { bShowServiceitemFilterBar = false; }
        }

        /// <summary>
        /// 显示服务项目分类工具栏
        /// </summary>
        public bool ShowServiceItemCategoryToolbar
        {
            set
            {
                rbClass.Visible = value;
            }
        }

        /// <summary>
        /// 服务项目编辑状态
        /// </summary>
        public bool ServiceItemEditMode
        {
            get { return bServiceItemEditMode; }
            set { bServiceItemEditMode = value; }
        }

        /// <summary>
        /// 服务项目分类编辑状态
        /// </summary>
        public bool ServiceItemCategoryEditMode
        {
            get { return bServiceItemCategoryEditMode; }
            set { bServiceItemCategoryEditMode = value; }
        }

        /// <summary>
        /// 显示服务项目工具栏
        /// </summary>
        public bool ShowServiceItemToolbar
        {
            set { rbServiceItem.Visible = value; }
        }

        public bool ShowServiceItemSearch
        {
            set { serviceItemSearch1.Visible = value; }
        }

        public ServiceItemControl()
        {
            InitializeComponent();
            
            sDefaultRowFilter = string.Format("{0}='{1}'", DBEntityServiceItem.FieldName.STATE, DBEntityServiceItem.ENUM_STATE.C0A);
        }

        public void Init()
        {
            InitCategoryTree();
            InitServiceItem();

            serviceItemSearch1.ShowSearchButton = false;
            serviceItemSearch1.onSearchKeyWordChanged = this.FilterServiceItem;
        }

        #region 服务项目分类

        private void InitCategoryTree()
        {
            string error = string.Empty;
            dsServiceItemCategory = new DataSet();
            BussinessProxyManager.Instance.QueryServiceItemCategory(string.Empty, out dsServiceItemCategory, out error);
            DataRow[] drFinds = dsServiceItemCategory.Tables[0].Select("SCATEGORYID=0");
            if (drFinds.Length <= 0)
            {
                DataRow drNew = dsServiceItemCategory.Tables[0].NewRow();
                drNew[DBEntityServiceItemCategory.FieldName.SCATEGORYID] = 0;
                drNew[DBEntityServiceItemCategory.FieldName.SNAME] = "所有";
                drNew[DBEntityServiceItemCategory.FieldName.SPARENTCATEGORYID] = -1;
                dsServiceItemCategory.Tables[0].Rows.InsertAt(drNew, 0);
            }
            dsServiceItemCategory.AcceptChanges();

            TreeListNode fNode = tlCategory.FocusedNode;

            tlCategory.KeyFieldName = DBEntityServiceItemCategory.FieldName.SCATEGORYID;
            tlCategory.ParentFieldName = DBEntityServiceItemCategory.FieldName.SPARENTCATEGORYID;
            tlCategory.DataSource = dsServiceItemCategory.Tables[0].DefaultView;

            ExpandNodes();

            if (fNode != null)
            {
                tlCategory.FocusedNode = fNode;
            }
        }

        public void ExpandNodes()
        {
            if (tlCategory.Nodes.Count > 0)
            {
                tlCategory.Nodes[0].Expanded = true;
                foreach (TreeListNode node in tlCategory.Nodes[0].Nodes)
                {
                    node.Expanded = true;
                }
            }
        }

        private void btnAddCategory_Click(object sender, EventArgs e)
        {
            if (bServiceItemCategoryEditMode == false)
                return;

            int iParentCategoryID = -1;
            if (tlCategory.FocusedNode == null)
                iParentCategoryID = 0;

            if (tlCategory.FocusedNode != null && tlCategory.FocusedNode.Level > 1)
            {
                MsgBox.MsgInfo("系统不允许4级分类。");
                return;
            }

            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(tlCategory.FocusedNode);
            if (drv != null)
            {
                iParentCategoryID = Convert.ToInt32(drv[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            }

            DBEntityServiceItemCategory category = new DBEntityServiceItemCategory();
            category.SPARENTCATEGORYID = iParentCategoryID;
            frmServiceItemCategoryAdd form = new frmServiceItemCategoryAdd(category);
            form.StartPosition = FormStartPosition.CenterScreen;
            form.Flag = ControlClassModeEnum.emInsert;
            if (form.ShowDialog() == DialogResult.OK)
            {
                InitCategoryTree();
            }
        }

        private void btnModifyCategory_Click(object sender, EventArgs e)
        {
            if (bServiceItemCategoryEditMode == false)
                return;

            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(tlCategory.FocusedNode);
            if (drv == null)
            {
                MsgBox.MsgInfo("请先选择要修改的分类。");
                return;
            }

            DataRow dr = drv.Row;
            int iCategoryID = Convert.ToInt32(dr[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            if (iCategoryID == 0)
                return;

            DBEntityServiceItemCategory category = new DBEntityServiceItemCategory(dr);
            frmServiceItemCategoryAdd form = new frmServiceItemCategoryAdd(category);
            form.StartPosition = FormStartPosition.CenterScreen;
            form.Flag = ControlClassModeEnum.emEdit;
            if (form.ShowDialog() == DialogResult.OK)
            {
                InitCategoryTree();
            }
        }

        private void btnDeleteCategory_Click(object sender, EventArgs e)
        {
            if (bServiceItemCategoryEditMode == false)
                return;

            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(tlCategory.FocusedNode);
            if (drv == null)
            {
                MsgBox.MsgInfo("请先选择要删除的分类。");
                return;
            }

            DataRow dr = drv.Row;
            int iCategoryID = Convert.ToInt32(dr[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            if (iCategoryID == 0)
                return;
            DBEntityServiceItemCategory category = new DBEntityServiceItemCategory(dr);
            string sMsg = "删除分类会将当前分类下的服务项目归于其上级分类下，确定要删除吗？";
            if (MsgBox.MsgQue(sMsg))
            {
                string error = string.Empty;
                bool bFlag = BussinessProxyManager.Instance.DeleteServiceItemCategory(category.SCATEGORYID, out error);
                if (bFlag == false)
                {
                    MsgBox.MsgErr(error);
                    return;
                }
                InitCategoryTree();
            }

        }

        private void tlCategory_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(tlCategory.FocusedNode);
            if (drv == null)
                return;

            int iCategoryID = Convert.ToInt32(drv[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            if (iCategoryID == 0)
            {
                btnModifyCategory.Enabled = false;
                btnDeleteCategory.Enabled = false;
            }
            else
            {
                btnModifyCategory.Enabled = true;
                btnDeleteCategory.Enabled = true;
            }
            
            DataView dv = gvServiceItem.DataSource as DataView;
            dv.RowFilter = GetServiceItemRowFilter();
        }

        private void GetSubClassIDs(TreeListNode node, ref string IDs)
        {
            if (node.Nodes.Count > 0)
            {
                foreach (TreeListNode subNode in node.Nodes)
                {
                    GetSubClassIDs(subNode, ref IDs);
                }
            }
            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(node);
            if (drv != null)
            {
                string sCategoryID = drv[DBEntityServiceItemCategory.FieldName.SCATEGORYID].ToString();
                if (IDs == string.Empty)
                    IDs = sCategoryID;
                else
                    IDs += "," + sCategoryID;
            }
        }

        #endregion

        #region 服务项目

        private string GetServiceItemRowFilter()
        {
            string sRowFilter = string.Empty;
            sRowFilter = GetCategoryFilter(tlCategory.FocusedNode);
            if (serviceItemSearch1.Keyword != string.Empty)
            {
                if (sRowFilter == string.Empty)
                    sRowFilter = GetSearchFilter(serviceItemSearch1.Keyword);
                else
                    sRowFilter += " AND " + GetSearchFilter(serviceItemSearch1.Keyword);
            }
            if (!chkShowAllItems.Checked)
            {
                if (sRowFilter == string.Empty)
                    sRowFilter = sDefaultRowFilter;
                else
                    sRowFilter += " AND " + sDefaultRowFilter;
            }
            return sRowFilter;
        }

        private string GetCategoryFilter(TreeListNode node)
        {
            string sCategoryFilter = string.Empty;
            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(node);
            if (drv == null)
                return string.Empty;

            int iCategoryID = Convert.ToInt32(drv[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            if (iCategoryID != 0)
            {
                string IDs = string.Empty;
                GetSubClassIDs(tlCategory.FocusedNode, ref IDs);
                
                sCategoryFilter = string.Format("{0} in ({1})", DBEntityServiceItem.FieldName.SCATEGORYID, IDs);
            }
            return sCategoryFilter;
        }

        private string GetSearchFilter(string keyword)
        {
            return string.Format("({0} like '%{1}%' OR {2} like '%{1}%')", DBEntityServiceItem.FieldName.SNAME, keyword, DBEntityServiceItem.FieldName.SERVICEITEMCODE);
        }

        private void FilterServiceItem(string sKeyword)
        {
            gdServiceItem.DataSource = null;
            gdServiceItem.DataSource = dsServiceItem.Tables[0].DefaultView;
            DataView dv = dsServiceItem.Tables[0].DefaultView;
            dv.RowFilter = GetServiceItemRowFilter();
        }

        public void InitServiceItem()
        {
            string error = string.Empty;
            dsServiceItem = new DataSet();
            BussinessProxyManager.Instance.QueryServiceItem(string.Empty, out dsServiceItem, out error);

            DataColumn dc = new DataColumn("SELECTED", typeof(int));
            dc.DefaultValue = 0;
            dsServiceItem.Tables[0].Columns.Add(dc);

            dc = new DataColumn("STATENAME");
            dsServiceItem.Tables[0].Columns.Add(dc);

            foreach (DataRow dr in dsServiceItem.Tables[0].Rows)
            {
                string sState = dr[DBEntityServiceItem.FieldName.STATE].ToString();
                dr["STATENAME"] = DBEntityServiceItem.ENUM_STATE.EnumStrToChineseStr(sState);
            }
            dsServiceItem.AcceptChanges();

            gdServiceItem.DataSource = null;
            gdServiceItem.DataSource = dsServiceItem.Tables[0].DefaultView;
            dsServiceItem.Tables[0].DefaultView.RowFilter = GetServiceItemRowFilter();

            if (bServiceItemEditMode)
            {
                gcSelect.VisibleIndex = -1;
            }
            else
            {
                gcSelect.VisibleIndex = 0;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            int iCategoryID = 0;
            DataRowView drv = (DataRowView)tlCategory.GetDataRecordByNode(tlCategory.FocusedNode);
            if (drv != null)
            {
                iCategoryID = Convert.ToInt32(drv[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            }
            DBEntityServiceItem serviceItem = new DBEntityServiceItem();
            serviceItem.SCATEGORYID = iCategoryID;
            frmServiceItemAdd form = new frmServiceItemAdd(serviceItem);
            if (form.ShowDialog() == DialogResult.OK)
            {
                InitServiceItem();
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            int iRowHandle = gvServiceItem.FocusedRowHandle;
            if (iRowHandle <= -1)
            {
                MsgBox.MsgInfo("请选择要更新的记录。");
                return;
            }

            DataRow dr = gvServiceItem.GetDataRow(iRowHandle);
            DBEntityServiceItem serviceItem = new DBEntityServiceItem(dr);
            frmServiceItemAdd form = new frmServiceItemAdd(serviceItem);
            form.Flag = ControlClassModeEnum.emEdit;
            if (form.ShowDialog() == DialogResult.OK)
            {
                InitServiceItem();
            }
        }

        #endregion

        private void btnSetState_Click(object sender, EventArgs e)
        {
            string sCaption = btnSetState.Text.Trim();
            int iRowHandle = gvServiceItem.FocusedRowHandle;
            if (iRowHandle <= -1)
            {
                MsgBox.MsgInfo(string.Format("请选择要{0}的服务项目。", sCaption));
                return;
            }
            
            DataRow dr = gvServiceItem.GetDataRow(iRowHandle);
            int iServiceItemID = Convert.ToInt32(dr[DBEntityServiceItem.FieldName.SERVICEITEMID]);

            string sState = "";
            string sStateText = "";
            if (sCaption == DBEntityServiceItem.ENUM_STATE.C0S_CHINESE)
            {
                sStateText = DBEntityServiceItem.ENUM_STATE.C0A_CHINESE;
                sState = DBEntityServiceItem.ENUM_STATE.C0S;
            }
            else
            {
                sStateText = DBEntityServiceItem.ENUM_STATE.C0S_CHINESE;
                sState = DBEntityServiceItem.ENUM_STATE.C0A;
            }
            string error = string.Empty;
            string sMessage = string.Format("确定要{0}此服务项目吗？", sCaption);
            if (MsgBox.MsgQue(sMessage))
            {
                bool bFlag = BussinessProxyManager.Instance.SetServiceItemState(iServiceItemID, sState, out error);
                if (bFlag == false)
                {
                    MsgBox.MsgInfo(error);
                    return;
                }

                btnSetState.Text = sStateText;
                InitServiceItem();
            }
        }

        private void gvServiceItem_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            int iRowHandle = gvServiceItem.FocusedRowHandle;
            if (iRowHandle < 0)
                return;

            DataRow dr = gvServiceItem.GetDataRow(iRowHandle);
            if (dr == null)
                return;
            string sState = dr[DBEntityServiceItem.FieldName.STATE].ToString();
            if (sState == DBEntityServiceItem.ENUM_STATE.C0A)
                btnSetState.Text = DBEntityServiceItem.ENUM_STATE.C0S_CHINESE;
            else
                btnSetState.Text = DBEntityServiceItem.ENUM_STATE.C0A_CHINESE;
            this.Refresh();
        }

        private void gvServiceItem_DoubleClick(object sender, EventArgs e)
        {
            if (bServiceItemEditMode)
            {
                btnModify_Click(null, null);
            }
        }

        private void tlCategory_DoubleClick(object sender, EventArgs e)
        {
            if (bServiceItemCategoryEditMode)
            {
                btnModifyCategory_Click(null, null);
            }
        }

        private void chkShowAllItems_CheckedChanged(object sender, DevComponents.DotNetBar.CheckBoxChangeEventArgs e)
        {
            DataView dv = (DataView)gdServiceItem.DataSource;
            dv.RowFilter = GetServiceItemRowFilter();
        }

        private void btnSetDetail_Click(object sender, EventArgs e)
        {
            int iHandler = gvServiceItem.FocusedRowHandle;
            if (iHandler < 0)
                return;

            DataRow dr = gvServiceItem.GetDataRow(iHandler);
            DBEntityServiceItem serviceItem = new DBEntityServiceItem(dr);
            frmStandardServiceItemPlan form = new frmStandardServiceItemPlan(serviceItem);
            form.ShowDialog();
        }

        public List<DBEntityServiceItem> GetSelectedServiceItemInfo()
        {
            List<DBEntityServiceItem> list = new List<DBEntityServiceItem>();
            DataView dv = gdServiceItem.DataSource as DataView;
            foreach (DataRowView drv in dv)
            {
                int iSelected = Convert.ToInt32(drv["SELECTED"]);
                if (iSelected == 0)
                    continue;

                DataRow dr = drv.Row;
                DBEntityServiceItem item = new DBEntityServiceItem(dr);
                list.Add(item);
            }
            return list;
        }

        private void tlCategory_DragEnter(object sender, DragEventArgs e)
        {
            if (bServiceItemEditMode == false)
                return;

            e.Effect = DragDropEffects.Copy;
        }

        private void tlCategory_DragDrop(object sender, DragEventArgs e)
        {
            if (bServiceItemEditMode == false)
                return;

            TreeList tree = sender as TreeList;
            string s = (string)e.Data.GetData(typeof(string));
            TreeListHitInfo hi = tlCategory.GetHitInfo(tlCategory.PointToClient(new Point(e.X, e.Y)));
            DataRowView drv = (DataRowView)tree.GetDataRecordByNode(hi.Node);
            if (drv == null)
                return;

            DataRow drFocusedItem = gvServiceItem.GetDataRow(gvServiceItem.FocusedRowHandle);
            if (drFocusedItem == null)
                return;

            DBEntityServiceItem item = new DBEntityServiceItem(drFocusedItem);
            item.SCATEGORYID = Convert.ToInt32(drv[DBEntityServiceItemCategory.FieldName.SCATEGORYID]);
            string error = string.Empty;
            bool bResult = BussinessProxyManager.Instance.UpdateServiceItem(item, out error);
            if (bResult == false)
            {
                MsgBox.MsgInfo("调整服务项目所属分类失败\r\n" + error);
                return;
            }
            InitServiceItem();
        }

        GridHitInfo hitInfo = null;
        private void gdServiceItem_MouseDown(object sender, MouseEventArgs e)
        {
            hitInfo = gvServiceItem.CalcHitInfo(new Point(e.X, e.Y));
        }

        private void gdServiceItem_MouseMove(object sender, MouseEventArgs e)
        {
            if (bServiceItemEditMode == false)
                return;

            if (hitInfo == null)
                return;
            if (e.Button != MouseButtons.Left)
                return;

            Point p = new Point(e.X, e.Y);
            if ((Math.Abs(p.X - hitInfo.HitPoint.X) > 5) || Math.Abs(p.Y - hitInfo.HitPoint.Y) > 5)
            {
                if (hitInfo.InRowCell)
                    gdServiceItem.DoDragDrop(gvServiceItem.GetRowCellDisplayText(hitInfo.RowHandle, hitInfo.Column), DragDropEffects.Copy);
                if (hitInfo.HitTest == GridHitTest.RowIndicator)
                {
                    string data = DataRow(gvServiceItem.GetDataRow(hitInfo.RowHandle));
                    gdServiceItem.DoDragDrop(data, DragDropEffects.Copy);
                }
            }

        }

        private string DataRow(DataRow drData)
        {
            string sData = "";
            if (drData != null)
            {
                foreach (object obj in drData.ItemArray)
                    sData = (sData == "" ? "" : sData + "; ") + obj.ToString();
            }
            return sData;
        }

    }
}
